#include <jni.h>
#include <string>
#include <android/log.h>

/*
 * 色彩空间转换 摄像头与编码器支持的格式不一致
 * nv21-COLOR_FormatYUV420PackedSemiPlanar
 * nv12-COLOR_FormatYUV420SemiPlanar
 * author: ZHG
 * date: 2020/3/18
 */

extern "C" JNIEXPORT void JNICALL
Java_com_zhg_videorecord_helper_YuvConver_convertNv21ToNv12(
        JNIEnv *env, jclass clazz, jbyteArray nv21Src, jbyteArray nv12Dst, jint framesize) {
    jbyte *pNv21Src = env->GetByteArrayElements(nv21Src, NULL);
    jbyte *pNv12Dst = env->GetByteArrayElements(nv12Dst, NULL);

    if (pNv21Src == NULL || pNv12Dst == NULL) {
        return;
    }
    //12和21前面的Y数据是相同的
    memcpy(pNv12Dst, pNv21Src, framesize);
    //framesize/2-1:U和V都是Y的四分一，两者加起来是二分一，
    //最后一个是i+1,所以framesize/2-1以免越界
    for (int i = 0; i < framesize / 2 - 1; i += 2) {
        //nv21 与nv12 的UV交换顺序
        pNv12Dst[i + framesize] = pNv21Src[i + framesize + 1];
        pNv12Dst[i + framesize + 1] = pNv21Src[i + framesize];
    }
    env->ReleaseByteArrayElements(nv21Src, pNv21Src, 0);
    env->ReleaseByteArrayElements(nv12Dst, pNv12Dst, 0);
    return;
}


